<template>
    <view class="fabu">
        <view class="feedback-title">
            分类
        </view>
        <view class="feedback-content">
            <view class="uni-list-cell-db" v-if="array_fenlei.length > 0">
                <picker @change="bindPickerChange" mode="selector" :value="index_fenlei" :range="array_fenlei">
                    <view class="uni-input">{{ array_fenlei[index_fenlei] }}</view>
                </picker>
            </view>
        </view>
        <view class="feedback-title">
            内容
            <text class="feedback-title-num">({{ content.length }}/200)</text>
        </view>
        <view class="feedback-content">
            <textarea class="feedback-textarea" v-model="content" maxlength="200" placeholder="请输入您的内容"/>
        </view>

        <view class="feedback-title">
            添加图片
            <text class="feedback-title-num">({{ imageList.length }}/6)</text>
        </view>
        <view class="feedback-image-box">

            <view class="feedback-image-item" v-for="(item, index) in imageList" :key="index">
                <view class="close-icon" @click="del(index)">
                    <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
                </view>
                <view class="image-box">
                    <image :src="item.url" mode="aspectFill"></image>
                </view>
            </view>

            <view v-if="imageList.length < 6" class="feedback-image-item" @click="addImage">
                <view class="image-box">
                    <uni-icons type="plusempty" size="50" color="#eee"></uni-icons>
                </view>
            </view>

        </view>

        <view class="feedback-title">
            发布人
        </view>
        <view class="feedback-content">
            <input type="text" v-model="nikename" placeholder="请输入发布人"/>
        </view>

        <view class="feedback-title">
            联系方式
            <span class="feedback-title_desc" v-show="mobile">(发布手机号需支付2金币)</span>
            <!-- <span class="feedback-title_jinbi">当前金币： {{ score }}</span> -->
        </view>
        <view class="feedback-content">
            <input type="text" v-model="mobile" placeholder="请输入您的联系方式"/>
        </view>

        <button class="feedback-button" type="primary" :disabled="submit_flag" @click="submit">发布</button>

    </view>
</template>

<script>
import wx from 'weixin-js-sdk';
import {
    mapState
} from 'vuex'

export default {
    data() {
        return {
            hashList: [],
            imageList: [],
            content: '',
            array_fenlei: [],
            array_id_fenlei: [],
            index_fenlei: 0,
            nikename: '',
            mobile: '',
            submit_flag: false,
            score: 0  // 金币
        }
    },
    computed: {
        ...mapState(['userinfo']),
        ...mapState(['notSeeCommentNum']),
    },
    watch: {
        // 检测userinfo的变化
        userinfo(newVal) {
            //userinfo 变好了
            console.log('watch userinfo变化了')
        }
    },
    onShow() {
        // 微信分享
        this.shareWx('', '发布')

        //未登录检测,跳转到登录页面
        if (!this.userinfo) {
            uni.showModal({
                content: '请先微信登录',
                success: function (res) {
                    if (res.confirm) {
                        uni.navigateTo({
                            url: '/pages/login/login?reffer=' + window.location.href
                        })
                    } else if (res.cancel) {
                        uni.switchTab({
                            url: '/pages/tabbar/index/index'
                        })
                    }
                }
            });

            return
        }

        // 刷新 userinfo
        this.getUserById();

        this.nikename = this.userinfo.nickname
        this.mobile = this.userinfo.mobile
        this.score = this.userinfo.score
        // 拿到分类
        this.getInfo();

        const that = this
        if (that.userinfo) {
            // 监听文章发送事件
            that.$api.getNotSeeCommentNum({
                user_id: that.userinfo.id
            }).then(result => {
                // 把登录信息赋值给 vuex 中的 notSeeCommentNum
                that.$store.dispatch('set_notseecommentnum', result)

                var count = that.notSeeCommentNum

                if (count > 99) {
                    count = '99+';
                }

                // uni.setTabBarBadge({
                // 	index: 3,
                // 	text: String(count)
                // })
            }).catch(err => {
                console.log(err)
            })
        }

    },
    methods: {
        // 根据id刷新用户
        getUserById() {
            this.$api.get_user_by_id({
                'id': this.userinfo.id
            }).then(res => {
                if (res.code == 1) {
                    this.user = res.data
                    // 把登录信息赋值给 vuex 中的 userinfo
                    this.$store.dispatch('set_userinfo', res.data)
                }
            })
        },
        /**
         * 恢复初始状态
         */
        toDefault() {
            this.hashList = [],
                this.imageList = [],
                this.content = '',
                this.array_fenlei = [],
                this.array_id_fenlei = [],
                this.index_fenlei = 0,
                this.submit_flag = false
        },
        // 获取图标
        getInfo() {
            const _this = this
            this.$api.get_info().then(res => {
                _this.icon = res.data.fenlei
                res.data.fenlei.forEach(function (value, item, array) {
                    _this.array_fenlei.push(value.name)
                    _this.array_id_fenlei.push(value.id)
                })

            })
        },
        bindPickerChange: function (e) {
            this.index_fenlei = e.target.value
        },
        //打开充值页面
        toPay() {
            //未登录检测,跳转到登录页面
            if (!this.userinfo) {
                this.login()
                return
            }
            uni.navigateTo({
                url: '/pages/pay/pay'
            })
        },
        // 上传
        submit() {
            if (!this.content) {
                uni.showToast({
                    title: '请输入内容',
                    icon: 'none'
                })
                return
            }

            if (this.mobile && !(/^1[3456789]\d{9}$/.test(this.mobile))) {
                uni.showToast({
                    title: '手机号码不合法，请重新输入~',
                    icon: 'none',
                    mask: true,
                })
                return false;
            }

            // 如果金币不足，省略mobile
            if (this.mobile && (/^1[3456789]\d{9}$/.test(this.mobile)) && this.score < 2) {

				uni.showModal({
					title: '金币不足，请充值?',
					success(res) {
						if (res.confirm) {
				
							// 去充值
							uni.navigateTo({
								url: '/pages/pay/pay'
							})
				
						} else if (res.cancel) {
							_this.mobile = ''
						}
					}
				})
            }
			
			

            this.submit_flag = true

            const _this = this

            this.$api.addarc({
                content: this.content,
                images: this.hashList,
                userid: this.userinfo.id,
                fenlei_id: this.array_id_fenlei[this.index_fenlei],
                contactname: this.nikename,
                contactmobile: this.mobile,
                type: 1, //1求助 2援助
            }).then(res => {
                if (res.ret == 1) {
                    uni.$emit('submitChange')
                    uni.showToast({
                        title: '发布成功',
                        icon: 'none',
                        mask: true,
                        success() {
                            setTimeout(function () {
                                // 刷新 userinfo
                                _this.getUserById();

                                uni.switchTab({
                                    url: '/pages/tabbar/index/index'
                                });
                                _this.toDefault()
                            }, 1000)

                        }
                    })


                } else {
                    this.submit_flag = false
                }
            }).catch(err => {
                uni.showToast({
                    title: '网络错误',
                    icon: 'none',
                    mask: true,
                })
            })
        },

        // 删除图片
        del(index) {
            this.imageList.splice(index, 1)
            this.hashList.splice(index, 1)
        },
        // 添加图片
        addImage() {
            let _this = this
            const count = 6 - this.imageList.length

            uni.chooseImage({
                count: 6, //最多运行上传几张图片
                success(res) {

                    uni.showLoading({
                        title: '上传中'
                    })

                    _this.$api.get_token_from_qiniu({}).then(result => {

                        if (result.ret == 1) {
                            var token = result.data.token;

                            const {
                                tempFilePaths
                            } = res

                            tempFilePaths.forEach((item, index) => {
                                // 处理 h5 多选的状况
                                if (index < count) {
                                    // _this.imageList.push({
                                    // 	url: item
                                    // })
                                }

                                uni.uploadFile({
                                    url: 'https://up-z1.qiniup.com/',
                                    filePath: item,
                                    name: 'file',
                                    formData: {
                                        'token': token
                                    },
                                    success: (uploadFileRes) => {
                                        let json = JSON.parse(uploadFileRes.data);
                                        // 上传到服务器fa_file中
                                        _this.$api.upload_qiniu({
                                            'hash': json.hash
                                        });

                                        _this.imageList.push({
                                            url: 'http://static.dadi30.com/' +
                                                json.hash + '-sl200'
                                        })
                                        _this.hashList.push(
                                            'http://static.dadi30.com/' + json
                                                .hash
                                        )

                                    },
                                    complete: () => {
                                        setTimeout(function () {
                                            uni.hideLoading();
                                        }, 250);
                                    },
                                });
                            })
                            // console.log(_this.imageList)

                        }

                    })

                }
            })
        }
    }
}
</script>

<style lang="scss">
.fabu {
    .feedback-title {
        margin: 15px;
        margin-bottom: 0;
        font-size: 14px;
        color: #666;
        overflow: hidden;

        .feedback-title_desc {
            font-size: 12px;
            margin-left: 12px;
        }

        .feedback-title_jinbi {
            text-align: right;
            display: inline-block;
            float: right;
        }

        .feedback-title-num {
            font-size: 12px;
            margin-left: 6px;
        }
    }

    .feedback-content {
        margin: 15px;
        padding: 10px;
        box-sizing: border-box;
        border: 1px solid #eee;

        .feedback-textarea {
            font-size: 12px;
            width: 100%;
            height: 100px;
        }
    }

    .feedback-image-box {
        display: flex;
        flex-wrap: wrap;
        padding: 10px;

        .feedback-image-item {
            position: relative;
            width: 33.33%;
            height: 0;
            padding-top: 33.33%;
            box-sizing: border-box;

            .image-box {
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: 5px;
                left: 5px;
                right: 5px;
                bottom: 5px;
                border: 1px solid #eee;
                border-radius: 5px;
                overflow: hidden;

                image {
                    width: 100%;
                    height: 100%;
                }
            }

            .close-icon {
                position: absolute;
                right: 0;
                top: 0;
                width: 22px;
                height: 22px;
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                background-color: #ff5a5f;
                z-index: 2;
            }
        }
    }

    .feedback-button {
        margin: 0 15px 20px 15px;
        background-color: $mk-base-color;
    }
}
</style>
